package com.example.baimao_tp.network

import android.util.Log
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

object RetrofitClient {
    private const val TAG = "RetrofitClient"

    // 支持多种服务器配置 - 优先使用HTTPS，失败时自动降级到HTTP
    private const val BASE_URL = "https://baimao-hz.cn:8888"
    private const val HTTP_BASE_URL = "http://baimao-hz.cn:8888"

    // 备选配置，可以根据实际情况切换：
    // private const val BASE_URL = "http://baimao-hz.cn:8888" // HTTP版本
    // private const val BASE_URL = "http://10.0.2.2:8888" // 模���器本地访问
    // private const val BASE_URL = "http://192.168.1.100:8888" // 局域网访问

    init {
        Log.d(TAG, "RetrofitClient初始化 - BASE_URL: $BASE_URL")
    }

    private val loggingInterceptor = HttpLoggingInterceptor().apply {
        level = HttpLoggingInterceptor.Level.BODY
        Log.d(TAG, "网络请求日志拦截器已设置 - Level: BODY")
    }

    // 创建信任所有证书的TrustManager（仅用于测试环境）
    private val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
        override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {}
        override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {}
        override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
    })

    private val okHttpClient = OkHttpClient.Builder()
        .connectTimeout(30, TimeUnit.SECONDS) // 连接超时30秒
        .readTimeout(30, TimeUnit.SECONDS)    // 读取超时30秒
        .writeTimeout(30, TimeUnit.SECONDS)   // 写入超时30秒
        .retryOnConnectionFailure(true)       // 连接失败时自动重试
        .hostnameVerifier { _, _ -> true }    // 信任所有主机名（仅用于测试）
        .sslSocketFactory(
            SSLContext.getInstance("SSL").apply {
                init(null, trustAllCerts, java.security.SecureRandom())
            }.socketFactory,
            trustAllCerts[0] as X509TrustManager
        ) // 信任所有SSL证书（仅用于测试）
        .addInterceptor { chain ->
            val request = chain.request()
            Log.d(TAG, "发起网络请求: ${request.method} ${request.url}")
            val startTime = System.currentTimeMillis()

            try {
                val response = chain.proceed(request)
                val endTime = System.currentTimeMillis()
                Log.d(TAG, "网络请求完成: ${response.code} - 耗时: ${endTime - startTime}ms")
                response
            } catch (e: Exception) {
                val endTime = System.currentTimeMillis()
                Log.e(TAG, "HTTPS请求失败: ${e.message} - 耗时: ${endTime - startTime}ms", e)

                // 如果是HTTPS请求失败，尝试降级到HTTP
                if (request.url.toString().startsWith("https://")) {
                    val httpUrl = request.url.newBuilder().scheme("http").build()
                    val httpRequest = request.newBuilder().url(httpUrl).build()
                    Log.d(TAG, "尝试降级到HTTP请求: ${httpRequest.url}")

                    try {
                        val response = chain.proceed(httpRequest)
                        Log.d(TAG, "HTTP请求成功: ${response.code} - 耗时: ${System.currentTimeMillis() - startTime}ms")
                        response
                    } catch (httpException: Exception) {
                        Log.e(TAG, "HTTP请求也失败: ${httpException.message}", httpException)
                        throw httpException
                    }
                } else {
                    throw e
                }
            }
        }
        .addInterceptor(loggingInterceptor)
        .build()

    val retrofit: Retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    val apiService: ApiService by lazy {
        Log.d(TAG, "创建ApiService实例")
        retrofit.create(ApiService::class.java)
    }

    // 获取BaseUrl用于错误提示
    fun getBaseUrl(): String = BASE_URL
}